/**
 * 通用调试日志系统
 * 支持所有JavaScript环境，无需额外依赖
 * 仿Google DevTools风格的调试面板
 */

import UniversalLogger from './core/UniversalLogger.js'

class DebugLogger {
  constructor(config = {}) {
    this.logger = new UniversalLogger(config)
    this.timers = new Map()
    this.groups = []

    // 自动检测并拦截全局axios（如果存在）
    this._autoDetectAxios()
  }

  /**
   * 自动检测并设置axios拦截器
   */
  _autoDetectAxios() {
    // 检测全局axios
    const checkAxios = () => {
      if (typeof window !== 'undefined' && window.axios) {
        this.logger._setupAxiosInterceptors(window.axios)
      }
      if (typeof global !== 'undefined' && global.axios) {
        this.logger._setupAxiosInterceptors(global.axios)
      }
      if (typeof axios !== 'undefined') {
        this.logger._setupAxiosInterceptors(axios)
      }
    }

    // 立即检测
    checkAxios()

    // 延迟检测（防止axios在后面加载）
    setTimeout(checkAxios, 1000)
    setTimeout(checkAxios, 3000)
  }

  // ==================== 基础日志方法 ====================

  /**
   * 调试日志
   */
  debug(...args) {
    return this.logger.debug(...args)
  }

  /**
   * 信息日志
   */
  info(...args) {
    return this.logger.info(...args)
  }

  /**
   * 普通日志
   */
  log(...args) {
    return this.logger.log(...args)
  }

  /**
   * 警告日志
   */
  warn(...args) {
    return this.logger.warn(...args)
  }

  /**
   * 错误日志
   */
  error(...args) {
    return this.logger.error(...args)
  }

  // ==================== Google DevTools风格方法 ====================

  /**
   * 表格输出（类似console.table）
   */
  table(data, columns = null) {
    if (!Array.isArray(data) && typeof data !== 'object') {
      return this.error('table() requires an array or object')
    }

    const tableData = {
      type: 'table',
      data,
      columns,
      title: 'Table',
    }

    return this.info('📊 Table:', tableData)
  }

  /**
   * 计时开始（类似console.time）
   */
  time(label = 'default') {
    this.timers.set(label, {
      startTime: Date.now(),
      label,
    })
    return this.info(`⏱️ Timer '${label}' started`)
  }

  /**
   * 计时结束（类似console.timeEnd）
   */
  timeEnd(label = 'default') {
    const timer = this.timers.get(label)
    if (!timer) {
      return this.warn(`⏱️ Timer '${label}' does not exist`)
    }

    const duration = Date.now() - timer.startTime
    this.timers.delete(label)

    const performanceData = {
      type: 'performance',
      label,
      duration,
      startTime: timer.startTime,
      endTime: Date.now(),
    }

    return this.info(`⏱️ ${label}: ${duration}ms`, performanceData)
  }

  /**
   * 计时日志（类似console.timeLog）
   */
  timeLog(label = 'default', ...args) {
    const timer = this.timers.get(label)
    if (!timer) {
      return this.warn(`⏱️ Timer '${label}' does not exist`)
    }

    const duration = Date.now() - timer.startTime
    return this.info(`⏱️ ${label}: ${duration}ms`, ...args)
  }

  /**
   * 分组开始（类似console.group）
   */
  group(label = 'Group') {
    this.groups.push(label)
    const groupData = {
      type: 'group_start',
      label,
      level: this.groups.length,
    }
    return this.info(`📁 ${'  '.repeat(this.groups.length - 1)}▼ ${label}`, groupData)
  }

  /**
   * 折叠分组开始（类似console.groupCollapsed）
   */
  groupCollapsed(label = 'Group') {
    this.groups.push(label)
    const groupData = {
      type: 'group_collapsed',
      label,
      level: this.groups.length,
      collapsed: true,
    }
    return this.info(`📁 ${'  '.repeat(this.groups.length - 1)}▶ ${label}`, groupData)
  }

  /**
   * 分组结束（类似console.groupEnd）
   */
  groupEnd() {
    const label = this.groups.pop() || 'Group'
    const groupData = {
      type: 'group_end',
      label,
      level: this.groups.length + 1,
    }
    return this.info(`📁 ${'  '.repeat(this.groups.length)}▲ End: ${label}`, groupData)
  }

  /**
   * 断言（类似console.assert）
   */
  assert(condition, message = 'Assertion failed', ...args) {
    if (!condition) {
      const assertData = {
        type: 'assertion',
        condition: false,
        message,
        args,
      }
      return this.error(`❌ Assertion failed: ${message}`, assertData, ...args)
    }

    return this.debug(`✅ Assertion passed: ${message}`)
  }

  /**
   * 计数器（类似console.count）
   */
  count(label = 'default') {
    if (!this._counters) {
      this._counters = new Map()
    }

    const currentCount = (this._counters.get(label) || 0) + 1
    this._counters.set(label, currentCount)

    const countData = {
      type: 'count',
      label,
      count: currentCount,
    }

    return this.info(`🔢 ${label}: ${currentCount}`, countData)
  }

  /**
   * 重置计数器（类似console.countReset）
   */
  countReset(label = 'default') {
    if (!this._counters) {
      this._counters = new Map()
    }

    this._counters.set(label, 0)
    return this.info(`🔢 Counter '${label}' reset`)
  }

  /**
   * 追踪调用栈（类似console.trace）
   */
  trace(message = 'Trace') {
    const stack = new Error().stack
    const traceData = {
      type: 'trace',
      message,
      stack,
    }
    return this.info(`🔍 ${message}`, traceData)
  }

  /**
   * 清空控制台（类似console.clear）
   */
  clear() {
    return this.logger.clear()
  }

  // ==================== 网络请求监控 ====================

  /**
   * 手动记录网络请求
   */
  networkRequest(method, url, config = {}) {
    const requestData = {
      id: this.logger._generateId(),
      type: 'manual',
      method: method.toUpperCase(),
      url,
      headers: config.headers || {},
      body: config.data || config.body,
      startTime: Date.now(),
      timestamp: new Date().toISOString(),
    }

    this.logger._addNetworkLog(requestData)
    return requestData.id
  }

  /**
   * 更新网络请求结果
   */
  networkResponse(requestId, response) {
    const networkLog = this.logger.networkLogs.find((log) => log.id === requestId)
    if (networkLog) {
      const endTime = Date.now()
      Object.assign(networkLog, {
        status: response.status || 200,
        statusText: response.statusText || 'OK',
        responseHeaders: response.headers || {},
        responseData: response.data || response.body,
        duration: endTime - networkLog.startTime,
        endTime,
        success: response.status >= 200 && response.status < 300,
      })
    }
  }

  // ==================== 高级功能 ====================

  /**
   * 目录输出（类似console.dir）
   */
  dir(object) {
    const dirData = {
      type: 'dir',
      object,
      properties: this._getObjectProperties(object),
    }
    return this.info('📋 Object:', dirData)
  }

  /**
   * XML输出（类似console.dirxml）
   */
  dirxml(element) {
    const xmlData = {
      type: 'dirxml',
      element: element.outerHTML || String(element),
      tagName: element.tagName,
      attributes: element.attributes ? Array.from(element.attributes) : [],
    }
    return this.info('🏷️ Element:', xmlData)
  }

  /**
   * 性能标记
   */
  mark(name) {
    const markData = {
      type: 'performance_mark',
      name,
      timestamp: Date.now(),
    }
    return this.info(`📍 Mark: ${name}`, markData)
  }

  /**
   * 性能测量
   */
  measure(name, startMark, endMark) {
    const measureData = {
      type: 'performance_measure',
      name,
      startMark,
      endMark,
      timestamp: Date.now(),
    }
    return this.info(`📏 Measure: ${name}`, measureData)
  }

  /**
   * 内存使用情况
   */
  memory() {
    let memoryInfo = {}

    if (typeof performance !== 'undefined' && performance.memory) {
      memoryInfo = {
        usedJSHeapSize: performance.memory.usedJSHeapSize,
        totalJSHeapSize: performance.memory.totalJSHeapSize,
        jsHeapSizeLimit: performance.memory.jsHeapSizeLimit,
      }
    } else if (typeof process !== 'undefined' && process.memoryUsage) {
      memoryInfo = process.memoryUsage()
    }

    const memoryData = {
      type: 'memory',
      ...memoryInfo,
    }

    return this.info('💾 Memory Usage:', memoryData)
  }

  // ==================== 实用工具方法 ====================

  /**
   * 获取对象属性
   */
  _getObjectProperties(obj) {
    if (obj === null || obj === undefined) return {}

    const properties = {}
    try {
      for (const key in obj) {
        try {
          properties[key] = {
            value: obj[key],
            type: typeof obj[key],
            enumerable: Object.propertyIsEnumerable.call(obj, key),
          }
        } catch (e) {
          properties[key] = {
            value: '[Error accessing property]',
            type: 'error',
            enumerable: false,
          }
        }
      }
    } catch (e) {
      // 处理特殊对象
    }

    return properties
  }

  /**
   * 格式化颜色输出（浏览器支持）
   */
  styled(message, styles) {
    if (typeof window !== 'undefined' && window.console && console.log.toString().includes('[native code]')) {
      console.log(`%c${message}`, styles)
    }
    return this.log(message, { type: 'styled', styles })
  }

  // ==================== 配置和状态管理 ====================

  /**
   * 获取连接状态
   */
  getStatus() {
    return this.logger.getConnectionStatus()
  }

  /**
   * 获取日志
   */
  getLogs(level = null) {
    return this.logger.getLogs(level)
  }

  /**
   * 获取网络日志
   */
  getNetworkLogs() {
    return this.logger.getNetworkLogs()
  }

  /**
   * 更新配置
   */
  updateConfig(config) {
    this.logger.updateConfig(config)
  }

  /**
   * 清空本地日志
   */
  clearLocal() {
    this.logger.clearLocal()
    this.timers.clear()
    this.groups = []
    if (this._counters) {
      this._counters.clear()
    }
  }

  /**
   * 手动刷新发送队列
   */
  flush() {
    return this.logger.flush()
  }

  /**
   * 获取底层Logger实例
   */
  getLogger() {
    return this.logger
  }
}

// 创建全局实例
const Debug = new DebugLogger()

// 自动设置全局拦截器
if (typeof window !== 'undefined') {
  window.DebugLogger = Debug
}

export default Debug
export { DebugLogger }


